import React, { useState } from 'react'
import { SchemaForm, Item, Submit, Observer, Layout, SchemaType } from '@amazebird/antd-schema-form'
import Moment from 'moment'
import ReactJson from 'react-json-view'

const initialValues = {
  name: '王大捶',
  interest: '电影,音乐',
  birthday: '1991-10-23',
  address: {
    area: '',
    detail: ''
  },
  workDuring: {
    start: '2015-09-20',
    end: '2021-09-30'
  }
}

const schema: SchemaType = {
  name: {
    label: '姓名',
    component: 'Input'
  },
  greet: {
    component: 'Text',
    value: Observer({
      watch: 'name',
      action: (name) => {
        return `欢迎[${name}]进入直播间！`
      }
    }),
    transform: {
      output: false
    }
  },
  interest: {
    label: '兴趣',
    component: 'Checkbox',
    options: [{ label: '电影', value: '电影' }, { label: '音乐', value: '音乐' }, { label: '旅游', value: '旅游' }],
    transform: {
      input: (value) => {
        if (value && typeof value === 'string') {
          return value.split(',')
        }
        return []
      },
      output: (value = []) => value.join()
    }
  },
  birthday: {
    label: '出生日期',
    component: 'DatePicker',
    transform: {
      input: (value) => { if (value) return Moment(value) },
      output: (value) => { if (value) return value.format('yyyy-MM-DD') }
    }
  },
  workDuring: {
    label: '工作时间',
    component: 'RangePicker',
    transform: {
      input: (value) => {
        if (value) {
          const { start, end } = value
          return [Moment(start), Moment(end)]
        }
      },
      output: (value) => {
        if (value) {
          const [start, end] = value
          return {
            start: start.format('yyyy-MM-DD'),
            end: end.format('yyyy-MM-DD')
          }
        } else {
          return {}
        }
      }
    }
  }

}

function Demo() {
  const [formData, setFormData] = useState()
  function onFinish(data) {
    const formData = JSON.stringify(data, null, 2)
    console.info(formData)
    setFormData(data)
  }
  return (
    <>
      <SchemaForm schema={schema} initialValues={initialValues}>
        <Item field="name" />
        <Item field="greet" wrapperCol={{ offset: 8 }} />
        <Item field="interest" />
        <Item field="birthday" />
        <Item field="workDuring" />
        <Layout offset={8}>
          <Submit onFinish={onFinish} />
        </Layout>
        {
          formData &&
          <Layout offset={6}>
            <div>表单结果：</div>
            <ReactJson src={formData} name={null} displayDataTypes={false} />
          </Layout>
        }

      </SchemaForm>

    </>
  )
}

export default Demo
